class FeedbackPanel {
    constructor(homeApp) {
        this.app = homeApp;
        this.allFeedbackList = []; // 保存所有反馈数据
    }

    initFeedbackPanel() {
        // 初始化反馈面板
        this.loadFeedbackList();
        
        // 初始化搜索功能
        this.initSearch();
    }
    
    initSearch() {
        const searchInput = document.querySelector('#feedback-panel .search-input');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.handleSearch(e.target.value);
            });
        }
    }
    
    handleSearch(keyword) {
        if (!keyword) {
            // 如果搜索关键词为空，显示所有反馈
            this.renderFeedbackList(this.allFeedbackList);
            return;
        }
        
        // 根据关键词过滤反馈列表
        const filteredList = this.allFeedbackList.filter(feedback => {
            return (
                (feedback.content && feedback.content.includes(keyword)) ||
                (feedback.userPhone && feedback.userPhone.includes(keyword)) ||
                (feedback.userNickname && feedback.userNickname.includes(keyword)) ||
                (feedback.uid && feedback.uid.toString().includes(keyword))
            );
        });
        
        this.renderFeedbackList(filteredList);
    }

    async loadFeedbackList() {
        try {
            const response = await this.app.authenticatedFetch('/api/web/feedback/getAll');
            const resultText = await response.text();
            
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }
            
            if (result.code === 200) {
                this.allFeedbackList = result.data || [];
                this.renderFeedbackList(this.allFeedbackList);
            } else {
                console.error('获取意见反馈列表失败:', result.message);
                this.renderFeedbackList([]);
            }
        } catch (error) {
            console.error('获取意见反馈列表异常:', error);
            this.renderFeedbackList([]);
        }
    }

    renderFeedbackList(feedbackList) {
        const tbody = document.getElementById('feedback-table-body');
        if (!tbody) return;

        if (!feedbackList || feedbackList.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无意见反馈数据</td></tr>';
            return;
        }

        // 渲染反馈列表
        tbody.innerHTML = feedbackList.map(feedback => `
            <tr>
                <td>${feedback.id}</td>
                <td>${feedback.uid}</td>
                <td>${feedback.userPhone || '未知手机号'}</td>
                <td>${feedback.userNickname || '未知用户'}</td>
                <td>${feedback.content}</td>
                <td>${feedback.create_date ? new Date(feedback.create_date).toLocaleString() : ''}</td>
                <td>
                    <button class="btn small danger delete-feedback" data-id="${feedback.id}">删除</button>
                </td>
            </tr>
        `).join('');

        // 绑定删除事件
        tbody.querySelectorAll('.delete-feedback').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const id = e.target.getAttribute('data-id');
                this.deleteFeedback(id);
            });
        });
    }

    async deleteFeedback(id) {
        if (!confirm('确定要删除这条意见反馈吗？')) {
            return;
        }

        try {
            const response = await this.app.authenticatedFetch(`/api/web/feedback/delete/${id}`, {
                method: 'DELETE'
            });

            const resultText = await response.text();
            
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }
            
            if (result.code === 200) {
                alert('删除成功');
                // 重新加载列表
                this.loadFeedbackList();
            } else {
                alert('删除失败: ' + result.message);
            }
        } catch (error) {
            console.error('删除意见反馈异常:', error);
            alert('删除意见反馈异常: ' + error.message);
        }
    }
}